package com.atguigu.guli.service.vod.service.impl;

import com.atguigu.guli.common.base.result.ResultCodeEnum;
import com.atguigu.guli.service.base.exception.GuliException;
import com.atguigu.guli.service.vod.entity.Media;
import com.atguigu.guli.service.vod.mapper.MediaMapper;
import com.atguigu.guli.service.vod.service.LocalMediaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * @author jack
 * date 2024-07-02 18:07
 */
@Slf4j
@Service
public class LocalMediaServiceImpl implements LocalMediaService {

    @Resource
    private MediaMapper mediaMapper;

    @Override
    public String uploadVideo(MultipartFile file, String originalFilename) {
        long id = System.currentTimeMillis();
        String videoId = Long.toString(id);
        try {
            Media media = new Media();
            media.setId(id);
            media.setVideoName(file.getOriginalFilename());
            media.setBlobData(file.getBytes());
            int a = mediaMapper.insertMedia(media);
            return videoId;
        } catch (IOException e) {
            log.error("视频上传失败", e);
            throw new GuliException(ResultCodeEnum.VIDEO_UPLOAD_ALIYUN_ERROR);
        }
    }

    @Override
    public void removeVideo(String vodId) {
        int a = mediaMapper.deleteById(Long.parseLong(vodId));
    }

    @Override
    public void removeVideoByIdList(List<String> videoIdList) {
        videoIdList.forEach(e -> {
            mediaMapper.deleteById(Long.parseLong(e));
        });
    }

    @Override
    public ResponseEntity<Object> playVideo(Long videoId) {
        try {
            MediaType mediaType = MediaType.parseMediaType("video/mp4");
            Media video = mediaMapper.selectVideo(videoId);
            return ResponseEntity.ok()
                    .contentType(mediaType)
                    .body(video.getBlobData());
        } catch (Exception e) {
            log.error("播放视频出错");
            return ResponseEntity.notFound().build();
        }
    }
}
